﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace UdpClient
{
    internal class Program
    {

        private static int receivePort = 8012;
        static void Main(string[] args)
        {
            // 将字符串ip地址转化为ip地址
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            // 接收消息
            Socket receiveSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            // 接收方绑定ip地址
            receiveSocket.Bind(new IPEndPoint(ip, receivePort));
            // 字节数组
            byte[] buffer = new byte[1024];
            // 声明远程发送对象
            EndPoint sendRemote = (EndPoint)(new IPEndPoint(IPAddress.Any, 0));
            // 接收接收远程发送过来的消息
            int length = receiveSocket.ReceiveFrom(buffer, ref sendRemote);
            Console.WriteLine("接收到{0}消息:{1}", sendRemote.ToString(), Encoding.UTF8.GetString(buffer, 0, length).Trim());
            // 接收方停止接收状态
            receiveSocket.Shutdown(SocketShutdown.Receive);
            Console.ReadLine();
        }
    }
}
